<template>
  <scroll
    class="listview"
    ref="listview"
    :probeType="probeType"
    :data="list"
    :bounceTop="false"
    listenScroll
    @scroll="scroll"
  >
    <!-- 滚动列表 -->
    <ul>
      <li v-for="(group, g_i) in list" class="list-group" :key="g_i" ref="listGroup">
        <h2 class="list-group-title">{{ group.title }}</h2>
        <ul>
          <li @click="selectItem(item)" v-for="(item, i_i) in group.items" :key="i_i" class="list-group-item">
            <img class="avatar" v-lazy="item.avatar + `?param=${imageSize.s}y${imageSize.s}`" />
            <span class="name">{{ item.name }}</span>
          </li>
        </ul>
      </li>
    </ul>
    <!-- 快速入口 -->
    <div
      class="list-shortcut"
      ref="shortcutList"
      @touchstart.stop.prevent="onShortcutTouchStart"
      @touchmove.stop.prevent="onShortcutTouchMove"
    >
      <ul>
        <li
          v-for="(item, index) in shortcutList"
          :key="index"
          :data-index="index"
          class="item"
          :class="{ current: currentIndex === index }"
        >
          {{ item }}
        </li>
      </ul>
    </div>
    <!-- 固定标题 -->
    <div class="list-fixed" ref="fixed" v-show="fixedTitle">
      <div class="fixed-title">{{ fixedTitle }}</div>
    </div>

    <!-- loading -->
    <div class="loading-container" v-show="!list.length">
      <loading></loading>
    </div>
  </scroll>
</template>
<script>
import Scroll from 'components/scroll/scroll';
import Loading from 'components/loading/loading';
import { getData } from 'common/js/dom';
import { imageSize } from 'common/js/config';

const SHORTCUT_ITEN_HEIGHT = 18; // 快速入口每一个元素高度
const TITLE_HEIGHT = 30; // 滚动列表标题高度

export default {
  props: {
    list: {
      type: Array,
      default: [],
    },
  },
  watch: {
    list() {
      setTimeout(() => {
        this._calculateHeight();
      }, 20);
    },
    diff(newVal) {
      let fixedTop = newVal > 0 && newVal < TITLE_HEIGHT ? newVal - TITLE_HEIGHT : 0;
      // 频率优化
      if (this.fixedTop === fixedTop) {
        return;
      }
      this.fixedTop = fixedTop;
      // 做一个 transform 的动画
      this.$refs.fixed.style.transform = `translate3d(0,${fixedTop}px,0)`;
    },
  },
  data() {
    return {
      currentIndex: 0,
      scrollY: -1, // 当前滚动的Y
      groupHeight: [], // 滚动列表高度
      diff: -1, // 两个标题之间的高度差
      imageSize: imageSize,
    };
  },
  created() {
    this.touch = {};
    this.shortcutHeight = []; // 右侧小按钮高度列表
    this.probeType = 3;
  },
  computed: {
    shortcutList() {
      return this.list.map((group) => {
        return group.title.substr(0, 1);
      });
    },
    fixedTitle() {
      if (this.scrollY > 0) {
        return '';
      }
      return this.list[this.currentIndex] ? this.list[this.currentIndex].title : '';
    },
  },
  methods: {
    selectItem(item) {
      this.$emit('select', item);
    },
    onShortcutTouchStart(e) {
      this.touch.anchorIndex = parseInt(getData(e.target, 'index'));
      this.touch.y1 = e.touches[0].pageY;
      this._scrollTo(this.touch.anchorIndex);
    },
    onShortcutTouchMove(e) {
      this.touch.y2 = e.touches[0].pageY;
      let delta = ((this.touch.y2 - this.touch.y1) / SHORTCUT_ITEN_HEIGHT) | 0;
      let index = this.touch.anchorIndex + delta;
      this._scrollTo(index);
    },
    // 监听滚动事件
    scroll(pos) {
      this.scrollY = pos.y;
      // 没有高度数组就去计算出高度数组
      if (!this.groupHeight) {
        this._calculateHeight();
      }
      const groupHeight = this.groupHeight;
      // 当滚动到顶部，this.scrollY>0
      if (this.scrollY > 0) {
        this.currentIndex = 0;
        return;
      }
      // 在中间部分滚动
      for (let i = 0; i < groupHeight.length - 1; i++) {
        let height1 = groupHeight[i];
        let height2 = groupHeight[i + 1];
        if (-this.scrollY >= height1 && -this.scrollY < height2) {
          this.currentIndex = i;
          // 计算下一个列表距离顶部高度
          this.diff = height2 + this.scrollY;
          return;
        }
      }
      // 当滚动到底部，且-this.scrollY大于最后一个元素的上限
      this.currentIndex = groupHeight.length - 2;
    },
    refresh() {
      this.$refs.listview.refresh();
    },
    _scrollTo(index) {
      // 边界处理
      if (!index && index !== 0) {
        return;
      }
      if (index < 0) {
        index = 0;
      } else if (index > this.groupHeight.length - 2) {
        index = this.groupHeight.length - 2;
      }
      // 手动派发滚动事件
      // this.scroll({ y: -this.groupHeight[index] });
      this.$refs.listview.scrollToElement(this.$refs.listGroup[index], 0);
    },
    // 计算高度 用来做左右联动
    _calculateHeight() {
      // 初始化 shortcutHeight
      // this.shortcutHeight = [];
      // let h1 = this.$refs.shortcutList.getBoundingClientRect().top;
      // h1 += 20;
      // this.shortcutHeight.push(h1);
      // for (let i = 0; i < this.shortcutList.length; i++) {
      //   h1 += 20;
      //   this.shortcutHeight.push(h1);
      // }

      // 初始化 groupHeight
      this.groupHeight = [];
      const list = this.$refs.listGroup;
      let height = 0;
      this.groupHeight.push(height);
      for (let i = 0; i < list.length; i++) {
        height += list[i].clientHeight;
        this.groupHeight.push(height);
      }
    },
  },
  components: {
    Scroll,
    Loading,
  },
};
</script>
<style scoped lang="stylus">
@import "~common/stylus/variable"
  .listview
    position: relative
    width: 100%
    height: 100%
    overflow: hidden
    background: $color-background
    .list-group
      padding-bottom: 30px
      .list-group-title
        height: 30px
        line-height: 30px
        padding-left: 20px
        font-size: $font-size-small
        color: $color-text-l
        background: $color-highlight-background
      .list-group-item
        display: flex
        align-items: center
        padding: 20px 0 0 30px
        .avatar
          width: 50px
          height: 50px
          border-radius: 50%
        .name
          margin-left: 20px
          color: $color-text-l
          font-size: $font-size-medium
    .list-shortcut
      position: absolute
      z-index: 30
      right: 0
      top: 50%
      transform: translateY(-50%)
      width: 20px
      padding: 20px 0
      border-radius: 10px
      text-align: center
      background: $color-background-d
      font-family: Helvetica
      .item
        padding: 3px
        line-height: 1
        color: $color-text-l
        font-size: $font-size-small
        &.current
          color: $color-theme
    .list-fixed
      position: absolute
      top: 0
      left: 0
      width: 100%
      .fixed-title
        height: 30px
        line-height: 30px
        padding-left: 20px
        font-size: $font-size-small
        color: $color-text-l
        background: $color-highlight-background
</style>
